package com.xm.myapplication;


import com.xm.httpapi.BaseApi.CustomGsonConverterFactory;
import com.xm.myapplication.Util.log;
import java.security.cert.CertificateException;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.X509TrustManager;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;


/**
 * Created by dell on 2017/7/31.
 */

public class Api {

    public static ApiService SERVICE;

    /**
     * 请求超时时间
     */
 private static final int DEFAULT_TIMEOUT = 10;

    public static ApiService getDefault() {
        
        if (SERVICE == null) {
            X509TrustManager trustAllCert =
                    new X509TrustManager() {
                        @Override
                        public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {}

                        @Override
                        public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {

                        }

                        @Override
                        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                            return new java.security.cert.X509Certificate[]{};
                        }
                    };
           // SSLSocketFactory sslSocketFactory = new SSLSocketFactoryCompat(trustAllCert);

            HttpLoggingInterceptor loggingInterceptor=new  HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger(){

                @Override
                public void log(String message) {
                    log.e("httpinfo= "+message);
                }
            });
//            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(message -> {
//                //打印retrofit日志
//                log.e("retrofitBack = "+message);
//            });
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

            //手动创建一个OkHttpClient并设置超时时间
            OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();
            httpClientBuilder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
            httpClientBuilder.writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
            httpClientBuilder.readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);

            //httpClientBuilder.sslSocketFactory(sslSocketFactory, trustAllCert);
            httpClientBuilder .addInterceptor(loggingInterceptor);
          //  httpClientBuilder.addInterceptor(new ErrorInterceptor());
            /**
             * 对所有请求添加请求头
             */
//            httpClientBuilder.addInterceptor(chain -> {
////                Request request = chain.request();
////                okhttp3.Response originalResponse = chain.proceed(request);
////                return originalResponse.newBuilder().header("key1", "value1").addHeader("key2", "value2").build();
//                Request request = chain.request();
//                //获取request的创建者builder
//                Request.Builder builder = request.newBuilder();
//                //从request中获取headers，通过给定的键url_name
//                List<String> headerValues = request.headers(Url.URL_HEADER_TYPE);
//                //从request中获取原有的HttpUrl实例oldHttpUrl
//                HttpUrl oldHttpUrl = request.url();
//                if (headerValues != null && headerValues.size() > 0) {
//                    //如果有这个header，先将配置的header删除，因此header仅用作app和okhttp之间使用
//                    //  builder.removeHeader(HttpConfig.HEADER_KEY);
//                    //匹配获得新的BaseUrl
//                    String headerValue = headerValues.get(0);
//                    HttpUrl newBaseUrl = null;
//                    if (Url.URL_ONLINE.equals(headerValue)) {
//                        newBaseUrl = HttpUrl.parse(Url.BASE_URL_TEST);
//                    } else if (Url.URL_TEST.equals(headerValue)) {
//                        newBaseUrl = HttpUrl.parse(Url.BASE_URL_TEST);
//                    } else {
//                        newBaseUrl = oldHttpUrl;
//                    }
//                    //重建新的HttpUrl，修改需要修改的url部分
//                    HttpUrl newFullUrl = oldHttpUrl
//                            .newBuilder()
//                            .scheme(newBaseUrl.scheme())
//                            .host(newBaseUrl.host())
//                            .port(newBaseUrl.port())
//                            .build();
//
//                    //重建这个request，通过builder.url(newFullUrl).build()；
//                    //然后返回一个response至此结束修改
//                    return chain.proceed(builder.url(newFullUrl).build());
//                } else {
//                    return chain.proceed(request);
//                }
//            });
//            httpClientBuilder.addInterceptor(new Interceptor() {
//                @Override
//                public Response intercept(Chain chain) throws IOException {
//                    Request request = chain.request()
//                            .newBuilder()
//                            .addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
//                            .build();
//                    return chain.proceed(request);
//                }
//
//            });
            SERVICE = new Retrofit.Builder()
                    .client(httpClientBuilder.build())
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                   .baseUrl(BuildConfig.URL)
                    .addConverterFactory(CustomGsonConverterFactory.create())
                    .build().create(ApiService.class);
        }
        return SERVICE;
    }


}
